package api

import (
	"net/http"

	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
	"github.com/vsafonkin/crud/common"
)

type response struct {
	Message string
}

type Models struct {
	Crud common.Cruder
}

var md Models

func RunEchoServer(models Models) error {
	md = models

	e := echo.New()
	e.HideBanner = true
	e.Debug = true

	e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{
		Format: "[ECHO] ${method}, url:'${uri}', ${user_agent}, status:${status}\n",
	}))
	e.Use(middleware.Recover())

	e.GET("/", home)

	g := e.Group("/admin")
	g.Use(middleware.BasicAuth(func(username, pass string, c echo.Context) (bool, error) {
		if username == "bob" && pass == "admin" {
			return true, nil
		}
		return false, nil
	}))
	g.GET("/bob", bobController)

	e.GET("/:tablename", crudController)

	return e.Start(":8080")
}

func home(c echo.Context) error {
	return c.JSON(http.StatusOK, response{Message: "Hello"})
}

func bobController(c echo.Context) error {
	return c.JSON(http.StatusOK, response{Message: "Bob admin"})
}

func crudController(c echo.Context) error {
	tablename := c.Param("tablename")
	if column := c.QueryParam("col"); column != "" {
		value := c.QueryParam("val")
		row, err := md.Crud.GetByField(column, value, tablename)
		if err != nil {
			return c.JSON(http.StatusBadRequest, response{Message: err.Error()})
		}
		return c.JSON(http.StatusOK, row)
	}
	return c.JSON(http.StatusOK, response{Message: "List"})
}
